package cn.hls.web.tag;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import org.springframework.util.StringUtils;

import cn.hls.entity.Module;

/**
 *@fileName: ModuletreeTag.java
 *@package: com.bangni.web.tag
 *@Description:  自定义菜单标签
 *@author: yinghui.zhang
 *@email: uuhui@163.com
 *@date: 2015-4-17
 */
/**
 * @fileName: ModuletreeTag.java
 * @package: com.bangni.web.tag
 * @Description:
 * @author: yinghui.zhang
 * @email: uuhui@163.com
 * @date: 2015-4-18
 */
@SuppressWarnings("serial")
public final class ModuletreeTag extends TagSupport {
	// 定义模块集合
	private List<Module> moduleList;
	private Map<Long, Long> map = null;// 去重

	@Override
	public int doEndTag() throws JspException {
		JspWriter out = pageContext.getOut();
		StringBuilder result = new StringBuilder();
		try {
			// 添加菜单栏的名称
			result.append("<div id='left_content'><div id='menuheader'>系统菜单</div><div id='main'>");
			// 遍历模块
			for (Iterator<Module> it = moduleList.iterator(); it.hasNext();) {
				Module m = it.next();
				if (m.getPid()==null) { // 加载一级模块
					Long id = m.getId();
					String name = m.getName();
					String url = m.getUrl() == null ? "" : m.getUrl();
					result.append("<div class='Level1'>");
					// 判断url是否为空，若不为空则打开一个新的tab标签
					if (StringUtils.hasText(url)) {
						result.append("<a href='javascript:void(0);' name='" + id + "' onclick='mainAdmin.addNewTab(\"" + id + "\",\"" + name + "\",\"" + url + "\",true,\"系统菜单\");'>");
					} else {
						result.append("<a href='javascript:void(0);'>");
					}

					result.append("<div class=''></div><div class='left_text' style='cursor:pointer;'>" + name + "</div></a></div>");
					// 迭代下一级的模块
					setTagString(result, moduleList, id, 1);

				}
			}
			result.append("</div></div>");
			// 输出结果
			out.print(result.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return super.doEndTag();
	}

	

	/**
	 * 初始化结果集信息</br> 相关的css中的class样式为public.css中定义的样式<</br>
	 * mainAdmin.addNewTable 为mamin.js定义的方法
	 * 
	 * @param result
	 *            　输出结果集
	 * @param m
	 *            　模块对象
	 * @param num
	 *            序号
	 * @param modulelist
	 *            模块集合
	 */
	private void initResult(StringBuilder result, Module m, int num, List<Module> modulelist) {

		Long sid = m.getId();
		String sname = m.getName();
		String surl = m.getUrl() == null ? "" : m.getUrl();
		// 获得父类名称
		String pname = "";
		for (Iterator<Module> it = modulelist.iterator(); it.hasNext();) {
			Module module = it.next();
			//if (module.getId().intValue() == m.getParent().getId().intValue()) {
			if (module.getId().intValue() == m.getPid().intValue()) {
				pname = module.getName();
				break;
			}
		}
		result.append("<div class='Level" + num + "'>");
		if (StringUtils.hasText(surl)) {
			result.append("<a href='javascript:void(0);' name='" + sid + "' onclick='mainAdmin.addNewTab(\"" + sid + "\",\"" + sname + "\",\"" + surl + "\",true,\"" + pname + "\");'>");
		} else {
			result.append("<a href='javascript:void(0);'>");
		}
		result.append("<div class=''></div>");
		result.append("<div class='left_text' style='cursor:pointer;'>").append(sname).append("</div>");
		result.append("</a>");
		result.append("</div>");
	}

	private void setTagString(StringBuilder result, List<Module> modulelist, Long id, int num) {
		num++;
		boolean isSon = false;
		for (Module m : modulelist) {
			//if (m.getParent() != null && m.getParent().getId() != null && m.getParent().getId().intValue() == id.intValue()) {
			if (m.getPid() != null && m.getPid().intValue() == id.intValue()) {
				isSon = true;
				break;
			}
		}
		if (isSon) {
			result.append("<div class='all'>");
		}

		for (Iterator<Module> it = modulelist.iterator(); it.hasNext();) {
			Module m = it.next();
			//if (m.getParent() != null && m.getParent().getId() != null && m.getParent().getId().intValue() == id.intValue()) {
			if (m.getPid() != null && m.getPid().longValue() == id.longValue()) {
				Long sid = m.getId();
				
				initResult(result, m, num, modulelist);
				setTagString(result, modulelist, sid, num);
			}
		}
		if (isSon) {
			result.append("</div>");
		}
	}

	// 判断是否有子级
	@SuppressWarnings("unused")
	private boolean checkSon(List<Module> modulelist, Integer id) {
		boolean b = false;
		for (Iterator<Module> it = modulelist.iterator(); it.hasNext();) {
			Module m = it.next();
			if (m.getParent().getId() != null && m.getParent().getId().intValue() == id.intValue()) {
				b = true;
				break;
			}
		}
		return b;
	}

	@Override
	public int doStartTag() throws JspException {
		return super.doStartTag();
	}

	@SuppressWarnings("unchecked")
	public void setModulelist(Object object) {
		if (object == null) {
			moduleList = new ArrayList<Module>();
		} else {
			List<Module> templist = (List<Module>) object;
			// 去重
			moduleList = cleanModulelist(templist);

		}
	}

	/**
	 * 去除重复的模块名称
	 * 
	 * @param templist
	 *            　模块集合
	 */
	private List<Module> cleanModulelist(List<Module> templist) {
		moduleList = new ArrayList<Module>();
		map = new HashMap<Long, Long>();
		for (Iterator<Module> it = templist.iterator(); it.hasNext();) {
			Module m = it.next();
			Long id = m.getId();
			if (map.containsKey(id)) {
				continue;
			}
			map.put(id, id);
			moduleList.add(m);
		}
		return moduleList;
	}

}
